#owfs interface
import os, platform, sys, subprocess, logging

logger = logging.getLogger(__name__)

class OWFSException(Exception):
    pass

class Owfs:
    def __init__(self):
        self.mntPath = "./mnt/1wire/" if self.isWindows() else "/mnt/1wire/"
        self.rlog = "./reboot.log"

    def isWindows(self):
        return "windows" in platform.platform().lower()

    def check(self):
        try:
            self.dir("system")
            if os.path.isfile(self.rlog):
                os.remove(self.rlog)
        except:
            logger.debug("owcheck failed")
            self.recovery()
    
    def reboot(self):
        logger.debug("try reboot")
        if not os.path.isfile(self.rlog):
            f = open(self.rlog, 'w')
            f.write("1")
            f.close()
            logger.debug("reboot now")
            #subprocess.Popen(["/sbin/shutdown", "-r", "now"])
        sys.exit()
    
    def recovery(self):
        #try to recover filesystem
        logger.debug("OWFS RECOVERY")
        try:
            logger.debug("owdir")
            self.dir("system")
        except:
            try:
                logger.debug("umount 1wire")
                subprocess.Popen(["/bin/umount", self.mntPath]).wait()
                logger.debug("start owfs service")
                if (subprocess.Popen(["/usr/sbin/service", "owfs", "start"]).wait() != 0):
                    raise
            except:
                self.reboot()
        else:
            pass
            

    def read(self, path):
        try:
            f = open(self.mntPath + path, 'r')
            s = f.read()
            f.close()
            return s
        except Exception, e:
            logger.debug("owread failed: %s" % path)
            raise OWFSException(e)
    
    def write(self, path, value):
        try:
            f = open(self.mntPath + path, 'w')
            f.write(value)
            f.close()
        except Exception, e:
            logger.debug("owwrite failed: %s" % path)
            raise OWFSException(e)
    
    def dir(self, path):
        try:
            return os.listdir(self.mntPath + path)
        except Exception, e:
            logger.debug("owdir failed: %s" % path)
            raise OWFSException(e)
    
    
    

